<?php

namespace app\models;

use yii\db\Exception;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "{{%bug}}".
 *
 * @property int $id
 * @property int $project_id 项目id
 * @property int $to_user_id 处理人id
 * @property string $title 标题
 * @property string $content 内容
 * @property string|null $comment 备注
 * @property int $status 1待解决2已解决3不处理
 * @property int $level 1不影响使用2一般3中等4严重5毁灭
 * @property string $is_deleted 0正常1删除
 * @property string|null $create_time 创建时间
 * @property string|null $update_time
 */
class Bug extends BaseModel
{
    //1待解决
    const BUG_STATUS_PENDING = 1;
    //2已解决
    const BUG_STATUS_PROCESSED = 2;
    //3忽略
    const BUG_STATUS_IGNORE = 3;

    //1低2中3高
    const BUG_LEVEL_LOW = 1;
    const BUG_LEVEL_MEDIUM = 2;
    const BUG_LEVEL_HIGH = 3;

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%bug}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['project_id', 'title', 'content', 'level'], 'required','on' => self::SCENARIO_CREATE],
            [['project_id', 'to_user_id', 'status', 'level'], 'integer'],
            [['project_id', 'to_user_id', 'status', 'level'], 'default','value' => 0],
            [['content'], 'string'],
            [['create_time', 'update_time'], 'safe'],
            [['title', 'is_deleted'], 'string', 'max' => 100],
            [['comment'], 'string', 'max' => 1000],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'project_id' => '项目id',
            'to_user_id' => '处理人id',
            'title' => '标题',
            'content' => '内容',
            'comment' => '备注',
            'status' => '状态',
            'level' => '级别',
            'is_deleted' => '删除状态',
            'create_time' => '创建时间',
            'update_time' => 'Update Time',
        ];
    }

    public function fields()
    {
        return parent::fields(); // TODO: Change the autogenerated stub
    }

    public function scenarios()
    {
        $scenarios = parent::scenarios();
        $scenarios[self::SCENARIO_CREATE] = [
            'project_id',
            'to_user_id',
            'title',
            'content',
            'comment',
            'status',
            'level',
        ];
        $scenarios[self::SCENARIO_UPDATE] = [
            'to_user_id',
            'title',
            'content',
            'comment',
            'status',
            'level',
            'is_deleted',
        ];

        return $scenarios;
    }

    /**
     * 列表
     * @param int $projectId
     * @param int $status
     * @param int $level
     * @param int $toUserId
     * @param int $isDeleted
     * @param string $sortType
     * @param string $orderBy
     * @param int $cp
     * @param int $ps
     * @return array
     */
    public function dataList(
        int $projectId,
        int $status = 0,
        int $level = 0,
        int $toUserId = 0,
        int $isDeleted = 0,
        string $sortType = "DESC",
        string $orderBy = 'create_time',
        int $cp = 1,
        int $ps = 10
    )
    {
        if (!in_array($orderBy, ['create_time', 'id', 'update_time', 'status', 'level'])) {
            $orderBy = 'create_time';
        }

        $sort = strtoupper($sortType) === 'DESC' ? SORT_DESC : SORT_ASC;
        $query = self::find()->where(['project_id' => $projectId])->orderBy([$orderBy => $sort])->limit($ps)->offset(self::getOffsetByPageParam($ps, $cp));
        if ($isDeleted) {
            $query->andWhere(['is_deleted' => $isDeleted]);
        }else {
            $query->andWhere(['is_deleted' => 0]);
        }

        if ($toUserId) {
            $query->andWhere(['to_user_id' => $toUserId]);
        }
        if ($level) {
            $query->andWhere(['level' => $level]);
        }
        if ($status) {
            $query->andWhere(['status' => $status]);
        }

        $count = $query->count();
        $res = $query->asArray()->all();

        //获取userid
        $userId = array_unique(ArrayHelper::getColumn($res,'to_user_id'));
        $userInfo = $userId ? UserInfo::find()->select('nick_name,id')->where(['id' => $userId])->indexBy('id') ->all() : null;

        foreach ($res as &$v) {
            if (isset($userInfo[$v['to_user_id']])) {
                $v['to_user_info'] = $userInfo[$v['to_user_id']];
            } else {
                $v['to_user_info'] = null;
            }
        }

        return ['count' => $count, 'items' => $res];
    }

    /**
     * 详情
     * @param int $id
     * @return array|null
     */
    public function detail(int $id)
    {
        $res =  self::findOne(['id' => $id])->toArray();
        //项目详情
        $res['project_info'] = Project::findOne($res['project_id']);
        //用户详情
        $res['user_info'] = UserInfo::find()->select(['name','nick_name','email','type'])->where(['id' => $res['to_user_id']]) ->one();

        return $res;
    }

    /**
     * 更新数据
     * @param int $id
     * @param int $userId
     * @return array
     * @throws \yii\base\Exception
     */
    public function updateData(int $id,int $userId)
    {
        $record = self::findOne($id);
        if (!$record) {
            return ['没有找到数据', null];
        }

        $changeToUser = $changeStatus = null;

        //如果更改了to_user_id以及status则添加指派记录
        if ($record->to_user_id != $this->to_user_id) {
            $changeToUser = $this->to_user_id;
        }

        if ($record->status != $this->status) {
            $changeStatus = $this->status;
        }

        $record->setScenario(self::SCENARIO_UPDATE);

        //没有更改了to_user_id以及status
        if ($changeStatus === null && $changeToUser === null ) {
            $record->attributes = $this->attributes;
            if (!$record->save()) {
                return [current($record->getFirstErrors()), null];
            }

        }

        if ($changeToUser !== null || $changeStatus !== null) {

            $db = $this->getDb();
            $trans = $db->beginTransaction();
            try {
                $bugAssignModel = new BugAssign();
                $bugAssignModel->from_user_id = $userId;
                $bugAssignModel->to_user_id = intval($this->to_user_id > 0 ?: 0) ;
                $bugAssignModel->bug_id = $record->id;
                $bugAssignModel->status = $this->status;
                $bugAssignModel->comment = $this->comment;

                if(!$bugAssignModel->save()) {
                    throw new \yii\base\Exception('保存指派记录失败-'.current($bugAssignModel->getFirstErrors()));
                }

                $record->attributes = $this->attributes;
                if (!$record->save()) {
                throw new \yii\base\Exception('保存记录失败');
                }

                $trans->commit();
            }catch (Exception $e) {
                $trans->rollBack();
                return [$e->getMessage(), null];
            }

        }

        return [null, $record];
    }


}
